using System;
using System.Threading;

// This value type encapsulates mutex locking and unlocking
internal struct MutexLock : IDisposable {
   private Mutex m_mutex;

   // This constructor acquires a lock on the mutex
   public MutexLock(Mutex m) { 
      m_mutex = m; 
      m_mutex.WaitOne(); 
   }

   // This Dispose method releases the lock on the mutex
   public void Dispose() {
      m_mutex.ReleaseMutex();
   }
}

public sealed class Program {
   // This method demonstrates how to use the MutexLock effectively
   public static void Main() {
      // Construct a mutex object
      Mutex m = new Mutex();

      // Lock the mutex, do something, and unlock the mutex
      using (new MutexLock(m)) {
         // Perform some thread-safe operation in here...
      }
   }
}
